package main

import (
	"crypto/sha256"
	"encoding/hex"
	"log"
	"net/http"
	"time"
)

const (
	// Nginx 配置管理密码
	NginxConfigPassword = "}sQMZdkHC=F{0M61"
	// Session cookie 名称
	SessionCookieName = "nginx_config_session"
	// Session 有效期（24小时）
	SessionDuration = 24 * time.Hour
)

// 生成 session token
func generateSessionToken(password string) string {
	// 使用密码 + 时间戳生成唯一 token
	data := password + time.Now().String()
	hash := sha256.Sum256([]byte(data))
	return hex.EncodeToString(hash[:])
}

// 验证密码
func verifyPassword(password string) bool {
	return password == NginxConfigPassword
}

// 检查 session 是否有效
func isValidSession(r *http.Request) bool {
	cookie, err := r.Cookie(SessionCookieName)
	if err != nil {
		return false
	}

	// 这里简单验证 cookie 存在且不为空
	// 实际应用中应该存储 session 并验证
	return cookie.Value != ""
}

// 设置 session cookie
func setSessionCookie(w http.ResponseWriter, token string) {
	cookie := &http.Cookie{
		Name:     SessionCookieName,
		Value:    token,
		Path:     "/",
		MaxAge:   int(SessionDuration.Seconds()),
		HttpOnly: true,
		SameSite: http.SameSiteStrictMode,
	}
	http.SetCookie(w, cookie)
}

// 清除 session cookie
func clearSessionCookie(w http.ResponseWriter) {
	cookie := &http.Cookie{
		Name:     SessionCookieName,
		Value:    "",
		Path:     "/",
		MaxAge:   -1,
		HttpOnly: true,
	}
	http.SetCookie(w, cookie)
}

// Nginx 配置管理认证中间件
func nginxConfigAuthMiddleware(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// 检查是否已登录
		if isValidSession(r) {
			next(w, r)
			return
		}

		// 未登录，返回 401
		w.WriteHeader(http.StatusUnauthorized)
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.Write([]byte("Unauthorized"))
	}
}

// 处理登录请求
func nginxConfigLoginHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	password := r.FormValue("password")

	if verifyPassword(password) {
		// 密码正确，设置 session
		token := generateSessionToken(password)
		setSessionCookie(w, token)

		log.Println("Nginx config login successful")

		// 返回成功
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte(`{"success": true}`))
	} else {
		// 密码错误
		log.Println("Nginx config login failed: incorrect password")

		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte(`{"success": false, "error": "密码错误"}`))
	}
}

// 处理登出请求
func nginxConfigLogoutHandler(w http.ResponseWriter, r *http.Request) {
	clearSessionCookie(w)
	http.Redirect(w, r, "/", http.StatusSeeOther)
}
